package com.startx.http.system.tool;

import java.lang.reflect.Field;

import javax.persistence.Id;
import javax.persistence.Table;

/**
 * sql构建
 * @author minghu.zhang
 */
public class SqlBuilder {
	


	/**
	 * 获取Insert sql
	 * @param clz
	 * @return
	 */
	public static String getSaveSql(Class<?> clz) {
		Field[] supers = clz.getSuperclass().getDeclaredFields();
		Field[] fields = clz.getDeclaredFields();
		StringBuffer fieldBuffer = new StringBuffer();
		
		for (Field field : fields) {
			String name = field.getName();
			fieldBuffer.append(",").append(name);
		}
		
		for (Field field : supers) {
			if(field.isAnnotationPresent(Id.class)) {
				continue;
			}
			String name = field.getName();
			fieldBuffer.append(",").append(name);
		}
		
		StringBuffer sql = new StringBuffer("INSERT INTO ");
		Table table = clz.getAnnotation(Table.class);
		sql.append(table.name());
		sql.append("(");
		sql.append(fieldBuffer.substring(1));
		sql.append(") ");
		sql.append("VALUES");
		sql.append("(");
		sql.append(fieldBuffer.toString().replace(",", ",:").substring(1));
		sql.append(")");
		
		return sql.toString();
	}
	
}
